<template>
  <div class="fillcontain">
    <head-top></head-top>
    <div class="table_container">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="课程" prop="kecheng"> </el-table-column>
        <el-table-column label="时间" prop="class_time"> </el-table-column>
        <el-table-column label="地点" prop="address"> </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >添加课程</el-button
            >
            <!-- <el-button
                      size="mini"
                      type="Success"
                      @click="addFood(scope.$index, scope.row)">添加食品</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="Pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="20"
          layout="total, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </div>
      <el-dialog title="添加课程" v-model="dialogFormVisible">
        <el-form :model="selectTable">
          <el-form-item label="课程名称：" label-width="100px">
            <el-input v-model="selectTable.kecheng"></el-input>
          </el-form-item>
          <el-form-item label="地点" label-width="100px">
            <el-input v-model="selectTable.address"></el-input>
          </el-form-item>
          <el-form-item label="时间" label-width="100px">
            <!-- <el-time-picker v-model="class_time" placeholder="请选择时间">
            </el-time-picker> -->
            <el-date-picker
              v-model="class_time"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateShop">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import headTop from "../components/headTop";
import { baseUrl, baseImgPath } from "@/config/env";
import {
  cityGuess,
  getResturants,
  getResturantsCount,
  foodCategory,
  updateResturant,
  searchplace,
  deleteResturant,
  getAllUser,
  getGrade,
  addGrade,
  getTimeClass,
  addClassTime,
  delClassTime,
} from "@/api/getData";
export default {
  data() {
    return {
      baseUrl,
      baseImgPath,
      city: {},
      offset: 0,
      limit: 20,
      count: 0,
      tableData: [{ username: "342", nickname: "342", phone: "2423" }],
      currentPage: 1,
      selectTable: {},
      dialogFormVisible: false,
      categoryOptions: [],
      selectedCategory: [],
      address: {},
      class_time: "",
    };
  },
  created() {
    //
    this.getResturants();
    console.log(11111);
  },
  mounted() {
    // this.initData();
  },
  components: {
    headTop,
  },
  methods: {
    async initData() {},
    async getCategory() {
      try {
        const categories = await foodCategory();
        categories.forEach((item) => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: [],
            };
            item.sub_categories.forEach((subitem, index) => {
              if (index == 0) {
                return;
              }
              addnew.children.push({
                value: subitem.name,
                label: subitem.name,
              });
            });
            this.categoryOptions.push(addnew);
          }
        });
      } catch (err) {
        console.log("获取商铺种类失败", err);
      }
    },
    async getResturants() {
      let res = await getTimeClass();
      console.log(res);
      if (res.data.code == 200) {
        this.tableData = [];
        res.data.data.map((item) => {
          let tableData = {};
          tableData.kecheng = item.kecheng;
          tableData.class_time = this.formatDate(item.class_time);
          tableData.address = item.address;
          tableData.id = item.id;
          this.tableData.push(tableData);
        });
        if (res.data.data.length < 1) {
          let lastClass = {
            kecheng: "点击添加新的课程",
            class_time: "点击添加新的课程",
            address: "点击添加新的课程",
            addClass: "1",
          };
          this.tableData.push(lastClass);
        }
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) +
        "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
      var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + hh + mm + ss;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      this.getResturants();
    },
    async handleEdit(index, row) {
      this.selectTable = row;
      this.selectTable.address = "";
      this.selectTable.kecheng = "";

      this.dialogFormVisible = true;
    },
    addFood(index, row) {
      this.$router.push({ path: "addGoods", query: { restaurant_id: row.id } });
    },
    async handleDelete(index, row) {
      console.log(row);
      let params = new URLSearchParams();
      params.append("id", row.id);
      const res = await delClassTime(params);
      console.log(res);
      if (res.data.code == 200) {
        this.$message({
          type: "success",
          message: res.data.msg,
        });
        this.tableData.splice(index, 1);
      } else {
        throw new Error(res.data.msg);
      }
    },
    async querySearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const cityList = await searchplace(this.city.id, queryString);
          if (cityList instanceof Array) {
            cityList.map((item) => {
              item.value = item.address;
              return item;
            });
            cb(cityList);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    addressSelect(vale) {
      const { address, latitude, longitude } = vale;
      this.address = { address, latitude, longitude };
    },
    handleServiceAvatarScucess(res, file) {
      if (res.status == 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
    },
    beforeAvatarUpload(file) {
      const isRightType = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isRightType && isLt2M;
    },
    async updateShop() {
      this.dialogFormVisible = false;
      let class_time = new Date(this.class_time).getTime();

      let params = new URLSearchParams();
      params.append("class_time", class_time);
      params.append("kecheng", this.selectTable.kecheng);
      params.append("address", this.selectTable.address);
      let res = await addClassTime(params);

      if (res.data.code == 200) {
        this.$message({
          type: "success",
          message: "添加成功",
        });

        this.getResturants();
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
  },
};
</script>

<style lang="less">
@import "../style/mixin";
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.table_container {
  padding: 20px;
}
.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
